import BangumiCardList from '@/pages/Search/components/BangumiCardList';
import DoubanCardList from '@/pages/Search/components/DoubanCardList';
import { searchSubjectV0UsingPOST } from '@/services/otherworldly-station-backend/BangumiController';
import { searchMovieUsingPOST } from '@/services/otherworldly-station-backend/DoubanController';
import { Card, Col, Layout, Row, Spin } from 'antd';
import Search from 'antd/es/input/Search';
import { Content } from 'antd/es/layout/layout';
import React, { useState } from 'react';
import styles from './index.less';

type tabKeyType = 'all' | 'douban' | 'bangumi';
const searchBangumiParams = {
    filter: {
        /** 上映日期 例：[ ">=2020-07-01", "<2020-10-01" ] */
        airDate: [],
        /** 是否包含NSFW */
        nsfw: true,
        /** 评分 例：[ ">10", "<=18" ] */
        rank: [],
        /** 评级 例：[ ">10", "<=18" ] */
        rating: [],
        /** 标签 */
        tag: [],
        /** 搜索类型 */
        type: [],
    },
    /** 搜索关键字 */
    keyword: '',
    /** 每页大小，默认20 */
    limit: 20,
    /** 开始偏移量，默认0 */
    offset: 0,
    /** 排序字段 */
    sort: 'rank',
};
const searchDoubanParams = {
    /** 获取条数，默认20 */
    count: 20,
    /** 搜索关键字 */
    searchKeys: '',
    /** 开始偏移量，默认0 */
    start: 0,
    /** 电影标签 */
    tag: '',
};
const FilmTelevision: React.FC = () => {
    const [tabKey, setTabKey] = useState<tabKeyType>('douban');
    const [loading, setLoading] = useState<boolean>(false);
    const [searchKey, setSearchKey] = useState<string>('');
    const [doubanPage, setDoubanPage] = useState<number>(1);
    const [bangumiPage, setBangumiPage] = useState<number>(1);
    const [doubanTabStatus, setDoubanTabStatus] = useState<boolean>(false);
    const [bangumiTabStatus, setBangumiTabStatus] = useState<boolean>(false);
    const [doubanCount, setDoubanCount] = useState<number>(0);
    const [bangumiCount, setBangumiCount] = useState<number>(0);
    const [doubanRecords, setDoubanRecords] = useState<API.DoubanSearchMovieVO[]>([]);
    const [bangumiRecords, setBangumiRecords] = useState<API.BangumiSearchSubjectSmallVO[]>([]);

    const searchBangumiData = async (limit: number, offset: number, value: string) => {
        setBangumiRecords([]);
        setLoading(true);
        searchSubjectV0UsingPOST({ ...searchBangumiParams, keyword: value, limit, offset })
            .then((res) => {
                if (res.code === 0) {
                    setBangumiCount(res.data?.total || 0);
                    setBangumiRecords(res.data?.records || []);
                    setSearchKey(value);
                    setBangumiTabStatus(false);
                }
            })
            .finally(() => {
                setLoading(false);
            });
    };

    const searchDoubanData = async (count: number, start: number, value: string) => {
        setDoubanRecords([]);
        setLoading(true);
        searchMovieUsingPOST({ ...searchDoubanParams, searchKeys: value, count, start })
            .then((res) => {
                if (res.code === 0) {
                    setDoubanCount(res.data?.total || 0);
                    setDoubanRecords(res.data?.records || []);
                    setSearchKey(value);
                    setDoubanTabStatus(false);
                }
            })
            .finally(() => {
                setLoading(false);
            });
    };

    const operationTabList = [
        {
            key: 'douban',
            tab: (
                <span>
                    豆瓣 {doubanCount ? <span style={{ fontSize: 14 }}>({doubanCount})</span> : ''}
                </span>
            ),
        },
        {
            key: 'bangumi',
            tab: (
                <span>
                    动漫{' '}
                    {bangumiCount ? <span style={{ fontSize: 14 }}>({bangumiCount})</span> : ''}
                </span>
            ),
        },
    ];
    // 渲染tab切换
    const renderChildrenByTabKey = (tabValue: tabKeyType) => {
        if (tabValue === 'bangumi') {
            return (
                <BangumiCardList
                    onSearchData={async (limit, offset, value) => {
                        await searchBangumiData(limit, offset, value);
                    }}
                    bangumiPage={bangumiPage}
                    setBangumiPage={(page: number) => setBangumiPage(page)}
                    searchKey={searchKey}
                    records={bangumiRecords}
                    recordsCount={bangumiCount}
                />
            );
        }
        if (tabValue === 'douban') {
            return (
                <DoubanCardList
                    onSearchData={async (count, start, value) => {
                        await searchDoubanData(count, start, value);
                    }}
                    doubanPage={doubanPage}
                    setDoubanPage={(page: number) => setDoubanPage(page)}
                    searchKey={searchKey}
                    records={doubanRecords}
                    recordsCount={doubanCount}
                />
            );
        }
        return null;
    };

    return (
        <>
            <Layout>
                <div className={styles.searchHeader}>
                    <Search
                        prefix="🔍"
                        style={{ verticalAlign: 'middle', width: '65%' }}
                        placeholder="输入想要看的影片"
                        enterButton="搜索"
                        size="large"
                        allowClear
                        onSearch={async (value) => {
                            // 有一个状态，记录我点击那个 tabKey， 并且搜索的时候重置这个状态
                            if (tabKey === 'bangumi') {
                                await searchBangumiData(20, 0, value).finally(() => {
                                    setDoubanTabStatus(true);
                                    setBangumiTabStatus(true);
                                });
                            } else if (tabKey === 'douban') {
                                await searchDoubanData(20, 0, value).finally(() => {
                                    setDoubanTabStatus(true);
                                    setBangumiTabStatus(true);
                                });
                            }
                        }}
                    />
                </div>
                <Spin spinning={loading}>
                    <Content>
                        <Row gutter={24}>
                            <Col lg={24} md={24} sm={24} xs={24} xxl={24} xl={24}>
                                <Card
                                    className={styles.tabsCard}
                                    bordered={false}
                                    tabList={operationTabList}
                                    activeTabKey={tabKey}
                                    onTabChange={async (_tabKey: string) => {
                                        if (_tabKey === 'bangumi' && bangumiTabStatus) {
                                            await searchBangumiData(20, 0, searchKey);
                                        } else if (_tabKey === 'douban' && doubanTabStatus) {
                                            await searchDoubanData(20, 0, searchKey);
                                        }
                                        setTabKey(_tabKey as tabKeyType);
                                    }}
                                >
                                    {renderChildrenByTabKey(tabKey)}
                                </Card>
                            </Col>
                        </Row>
                    </Content>
                </Spin>
            </Layout>
        </>
    );
};

export default FilmTelevision;
